import GameUtil from "../../../Script/Util/GameUtil";
import BaseDrag from "../../Base/BaseDrag";

const { ccclass, property } = cc._decorator;

interface IFilterConfig {
    id: number;
    name: '传单' | '礼品' | '箱' | '口红' | '咖啡';
    guTalk: string;
    skes: ISkeConfig[];
}

interface ISkeConfig {
    name: string;
    talk: string;
    fromX: number;
    toX: number;
    /** 拒绝 */
    isRefuse: boolean;
}

@ccclass
export default class FilterUI extends BaseDrag {

    @property({ type: [sp.Skeleton], tooltip: "左右人物动画" })
    private skes: sp.Skeleton[] = [];

    @property({ type: [cc.Node], tooltip: "" })
    private clicks: cc.Node[] = [];

    @property({ type: [cc.Node], tooltip: "拒绝按钮" })
    private btns: cc.Node[] = [];

    @property({ type: [cc.Node], tooltip: "员工说话气泡" })
    private bubbles: cc.Node[] = [];

    @property({ type: cc.Node, tooltip: "招聘说话节点" })
    private toast: cc.Node = null;

    private config: IFilterConfig = null;
    private complete: number[] = [];

    private configs: IFilterConfig[] = [
        {
            id: 1,
            name: '传单',
            guTalk: '菜市场降价啦',
            skes: [
                { name: 'nv_xian', talk: '面试先暂停，我去去就回', fromX: -2500, toX: -185, isRefuse: true },
                { name: 'nv_shouji', talk: '网上下单更便宜，还能送到家', fromX: 2500, toX: 205, isRefuse: false },
            ],
        },
        {
            id: 2,
            name: '礼品',
            guTalk: '为感谢两位的参与，我们准备了礼品，选一下吧',
            skes: [
                { name: 'nv_jidan', talk: '这筐鸡蛋多实惠，还是小顾会做人', fromX: -2500, toX: -185, isRefuse: true },
                { name: 'nv_huazhuangpin', talk: '没想到面个试还能领到化妆品小样', fromX: 2500, toX: 205, isRefuse: false },
            ]
        },
        {
            id: 3,
            name: '箱',
            guTalk: '这纸箱子你们帮我扔掉吧',
            skes: [
                { name: 'nv_xiang1', talk: '扔了多可惜，正好拿回家卖钱', fromX: -2500, toX: -185, isRefuse: true },
                { name: 'nv_xiang2', talk: '好的，面完试就去扔', fromX: 2500, toX: 205, isRefuse: false },
            ]
        },
        {
            id: 4,
            name: '口红',
            guTalk: '上班需要化妆，选一个合适的口红吧',
            skes: [
                { name: 'nv_idle2', talk: '这色多亮堂，还显年轻', fromX: -2500, toX: -185, isRefuse: false },
                { name: 'nv_idle3', talk: '这个颜色最亲和。', fromX: 2500, toX: 205, isRefuse: true },
            ]
        },
        {
            id: 5,
            name: '咖啡',
            guTalk: '我给两位准备了冰咖啡',
            skes: [
                { name: 'nv_beizi', talk: '不用了，我自己带了热水', fromX: -2500, toX: -185, isRefuse: true },
                { name: 'nv_kafei', talk: '谢谢你，瞬间就凉快下来了', fromX: 2500, toX: 205, isRefuse: false },
            ]
        },
    ]
    private getConfigById(id: number) {
        const config = this.configs.find((o) => o.id === id);
        return config;
    }

    protected onLoad() {
        super.onLoad();

        this.init();
    }

    private init() {
        this.toast.active = false;
        this.touchLayer.active = true;
        for (let i = 0; i < this.skes.length; i++) {
            const ske = this.skes[i];
            this.btns[i].active = false;
            this.bubbles[i].active = false;
            ske.setAnimation(0, 'nv_idle', true);
            // 进场
            cc.tween(this.skes[i].node.parent).to(0, { x: i == 0 ? -2500 : 2500 }).to(1, { x: i == 0 ? -185 : 205 }).start();
        }
    }

    private async updateBubble() {
        for (let i = 0; i < 2; i++) {
            this.bubbles[i].active = true;
            const talk = this.config.skes[i].talk;
            const lab = cc.find('lab', this.bubbles[i]).getComponent(cc.Label);
            GameUtil.effectWords(lab, talk, async () => {
                await GameUtil.sleep(300);
                this.bubbles[i].active = false;
            });
            await GameUtil.sleep(3000);
        }

        // 显示拒绝按钮
        for (let i = 0; i < 2; i++) {
            this.btns[i].active = true;
        }
    }

    private async setAnimation() {
        if (this.touchData.id < 1) return;

        this.touchLayer.active = false;
        this.config = this.getConfigById(this.touchData.id);
        this.touchData.id = -1;
        this.touchData.node.active = false;
        this.toast.active = true;
        const lab = cc.find('lab', this.toast).getComponent(cc.Label);
        GameUtil.effectWords(lab, this.config.guTalk, async ()=>{
            this.toast.active = false;
            await GameUtil.sleep(500);
            for (let i = 0; i < 2; i++) {
                GameUtil.playAnimation({ ske: this.skes[i], animName: this.config.skes[i].name, isLoop: true });
            }
        });
        await GameUtil.sleep(3000);
        this.updateBubble();
    }

    /** 拒绝左or右 */
    private select(index: number) {
        const data = this.config.skes[index];
        if (data?.isRefuse) {
            this.complete.push(this.config.id);
            this.finish();
        } else {
            console.log("拒绝错了，失败");
        }
    }

    /** 变大妈走和递合同 */
    private finish() {
        const data = { walk: 0, idle: 0 };
        const skeDatas = this.config.skes;
        for (let i = 0; i < skeDatas.length; i++) {
            if (skeDatas[i].isRefuse) {
                data.walk = i;
            } else {
                data.idle = i;
            }
        }
        this.skes[data.walk].setAnimation(0, this.config.id === 4 ? 'nv_lao3' : 'nv_lao', true);
        cc.tween(this.skes[data.walk].node.parent).delay(1).to(1, { x: skeDatas[data.walk].fromX }).call(()=>{
            this.init();
        }).start();

        // TODO 递合同
        console.log("递合同");
        if (this.complete.length >= this.clicks.length) {
            // TODO 结束 过关
            console.log("过关");
        }
    }

    private touchData: { id: number, node: cc.Node, startPos: cc.Vec2, isMove: boolean } = { id: -1, node: null, startPos: cc.v2(0, 0), isMove: false };
    public touchStart(event: cc.Event.EventTouch) {
        const pos = this.getClickPos(event);
        for (let i = 0; i < this.clicks.length; i++) {
            const intersect = GameUtil.intersect(this.clickRect, this.clicks[i]);
            if (intersect && this.clicks[i].active) {
                this.touchData = { id: i + 1, node: this.clicks[i], startPos: cc.v2(this.clicks[i].x, this.clicks[i].y), isMove: false };
            }
        }
    }

    public touchMove(event: cc.Event.EventTouch) {
        const pos = this.getClickPos(event);
        if (this.touchData.id > 0 && (Math.abs(this.clickRect.x - this.touchData.startPos.x) > 20 || Math.abs(this.clickRect.y - this.touchData.startPos.y) > 20)) {
            this.touchData.isMove = true;
            this.touchData.node.setPosition(cc.v2(pos.x, pos.y));
        } else {
            if (this.touchData.isMove) {
                this.touchData.node.setPosition(cc.v2(pos.x, pos.y));
            }
        }
    }

    public touchEnd(event: cc.Event.EventTouch) {
        for (let i = 0; i < this.skes.length; i++) {
            const tarage = this.skes[i].node.parent;
            const isInter = GameUtil.intersect(this.clickRect, tarage);
            if (isInter) {
                this.setAnimation();
                break;
            }
        }
    }

    public onBtnClicked(event: cc.Event.EventTouch) {
        for (let i = 0; i < this.btns.length; i++) {
            if (event.target === this.btns[i]) {
                console.log('选择:', i);
                this.select(i);
                break;
            }
        }
    }
}